package com.hxci.web.bean;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/images")
public class ImageServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("image/jpeg");
        // 绘制图片
        int charNum = 4;
        int width = 20 * charNum;
        int height = 30;
        // 创建一个内存图片
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获得绘制对象
        Graphics g = image.getGraphics();
        // 设置背景色
        g.setColor(Color.yellow);
        g.fillRect(0, 0, width, height);
        // 绘制边框
        g.setColor(Color.GRAY);
        g.drawRect(0, 0, width - 1, height - 1);
        // 输出验证码
        g.setColor(Color.RED);
        g.setFont(new Font("宋体", Font.BOLD, 20));
        // 随机产生4个字符
        String strCode = "ABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
        Random rand = new Random();
        // session保存验证码
        String msg = "";
        int x = 5;
        for (int i = 0; i < charNum; i++) {
            int index = rand.nextInt(32);
            String content = String.valueOf(strCode.charAt(index));
            msg+=content;
            g.setColor(new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256)));
            g.drawString(content, x, 22);
            x += 20;
        }

        request.getSession().setAttribute("sessionCode", msg);
        // 绘制干扰线
        g.setColor(Color.GRAY);
        for (int i = 0; i < 5; i++) {
            int x1 = rand.nextInt(width);
            int y1 = rand.nextInt(height);
            int x2 = rand.nextInt(width);
            int y2 = rand.nextInt(height);
            g.drawLine(x1, y1, x2, y2);
        }
        // 释放资源
        g.dispose();


        // 将图片输出到页面上
        ImageIO.write(image, "jpg", response.getOutputStream());

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}
